package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CP;
import ca.uhn.hl7v2.model.v24.group.MFN_M04_MF_CDM;
import ca.uhn.hl7v2.model.v24.message.MFK_M01;
import ca.uhn.hl7v2.model.v24.message.MFN_M04;
import ca.uhn.hl7v2.model.v24.segment.*;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Date;

public class PaymentConfirmationConvert extends AbstractMessageConvert {

    private static final Logger logger =LoggerFactory.getLogger(PaymentConfirmationConvert.class);
    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.PAYMENT_ONFIRMATION);
        MFN_M04 hl7Message = (MFN_M04) requestMessage.getHl7Message();
        MFN_M04_MF_CDM mfCdm = hl7Message.getMF_CDM();
        MFE mfe = mfCdm.getMFE();
        Varies[] varies = mfe.getMfe4_PrimaryKeyValueMFE();
        if(varies!=null && varies.length>0){
            for (Varies var : varies){
                GenericPrimitive primitive = (GenericPrimitive) var.getData();
                String[] temp = primitive.getValue().split("=");
                if (temp.length>1){
                    document.getRootElement().addElement(temp[0]).addText(temp[1] != null ? temp[1] : "");
                }else {
                    document.getRootElement().addElement(temp[0]).addText("");
                }
            }
        }
        PRC prc = mfCdm.getPRC();
        CP cp = prc.getPrice(0);
        document.getRootElement().addElement("TotalAmount").addText(cp.getCp1_Price().getMo2_Denomination().getValue());

        logger.info("200200 TO HIS XML:" + document.asXML());
        return document;



    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200200 from HIS XML = "+ message);
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        MFK_M01 mfk = new MFK_M01();
        mfk.initQuickstart("MFK_M01", "MFK_M01", "A");
        MSH msh = mfk.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = mfk.getMSA();
        String status = doc.getRootElement().elementTextTrim("IsSuccessed");
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg"));
        if (status.equals("1")) {
            MFI mfi = mfk.getMFI();

            BigDecimal CashPay = new BigDecimal(doc.getRootElement().elementTextTrim("CashPay")).setScale(2, BigDecimal.ROUND_CEILING);
            BigDecimal InsurePay = new BigDecimal(doc.getRootElement().elementTextTrim("InsurePay")).setScale(2, BigDecimal.ROUND_CEILING);
            BigDecimal AccountPay = new BigDecimal(doc.getRootElement().elementTextTrim("AccountPay")).setScale(2, BigDecimal.ROUND_CEILING);


            mfi.getMfi1_MasterFileIdentifier().getCe1_Identifier().setValue("CashPay=" + CashPay);
            mfi.getMfi1_MasterFileIdentifier().getCe2_Text().setValue("InsurePay=" + InsurePay);
            mfi.getMfi1_MasterFileIdentifier().getCe3_NameOfCodingSystem().setValue("AccountPay=" + AccountPay);
            mfi.getMfi1_MasterFileIdentifier().getCe4_AlternateIdentifier().setValue("ReceiptCode=" + doc.getRootElement().elementTextTrim("ReceiptCode"));
            mfi.getMfi1_MasterFileIdentifier().getCe5_AlternateText().setValue("Comment=" + doc.getRootElement().elementTextTrim("Comment"));
        }
        return mfk;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        MFN_M04 message = new MFN_M04();
        message.initQuickstart("MFN_M04", "MFN_M04", "A");
        MSH msh = message.getMSH();
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200200");
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh5_ReceivingApplication().getHd1_NamespaceID().setValue("HIS");
        msh.getMsh7_DateTimeOfMessage().getTs1_TimeOfAnEvent().setValue(new Date());
        msh.getMsh10_MessageControlID().setValue(IdGenerator.getUUID());

        MFN_M04_MF_CDM mfCdm = message.getMF_CDM();
        MFE mfe = mfCdm.getMFE();


        /**
         * patientId
         */
        addGenericPrimitive(mfe,"HISPatientID", "630818911208370555");

        /**
         * 医保卡卡号
         */
        addGenericPrimitive(mfe, "MedCardNo","");

        /**
         * 医保卡密码
         */

        addGenericPrimitive(mfe,"MedCardPwd", "");

        /**
         * 医保类型
         */

        addGenericPrimitive(mfe,"InsurTypeCode", "0");

        /**
         * 门特类型
         */

        addGenericPrimitive(mfe,"MtTypeCode", "");

        /**
         * 挂号ID
         */

        addGenericPrimitive(mfe, "RegID","6308189112082770555");

        /**
         * 缴费单号
         */
        addGenericPrimitive(mfe, "ReceiptPayNo","100618912195059706");

        /**
         * BusinessFrom 业务来源 * 1手机 2网站  3自助机  4窗口 5电话
         */

        addGenericPrimitive(mfe, "BusinessFrom","3");

        /**
         * 订单号
         */
        addGenericPrimitive(mfe,"OrderNo", "100618912195059706");

        /**
         * 支付方式
         */
        addGenericPrimitive(mfe,"PaymentType", "3");

        /**
         * 支付银行
         */
        addGenericPrimitive(mfe, "PaymentBank","");

        /**
         * DivisionID 医保分割id
         */
        addGenericPrimitive(mfe, "DivisionID","4002R1809131534322013");



        /**
         * 执行日期（当前时间）
         */
        addGenericPrimitive(mfe, "ExecuteDate","2018-09-13");

        /**
         * 执行时间（当前时间）
         */
        addGenericPrimitive(mfe, "ExecuteTime","15:34:10");



        /**
         * 订单信息说明
         */
        PRC prc = mfCdm.getPRC();
        prc.getPrc1_PrimaryKeyValuePRC().getCe1_Identifier().setValue("CLINIC");
        prc.getPrc1_PrimaryKeyValuePRC().getText().setValue("缴费");

        /**
         * 金额信息
         */
        CP cp = prc.getPrice(0);
        cp.getCp1_Price().getMo2_Denomination().setValue("448.00");


        return message;
    }



}
